package com.haipumi.back.actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.haipumi.beans.JsonModel;
import com.haipumi.beans.haipumi_databasetable;
import com.haipumi.biz.DatabaseBiz;
import com.haipumi.biz.impl.DatabaseBizImpl;
import com.haipumi.servlets.CommonServlet;
import com.haipumi.utils.CommonData;
import com.haipumi.utils.GetUrlUtil;
import com.haipumi.utils.LogUtil;
import com.haipumi.utils.ZipTool;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class BackDatabaseAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4522285619831094498L;
	
	private JsonModel jm=new JsonModel();
	@Autowired
	private DatabaseBiz databaseBiz;

	public JsonModel getJm() {
		return jm;
	}

	public void setJm(JsonModel jm) {
		this.jm = jm;
	}


	public String doDataBase(){
		String op=null;
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpServletResponse response =ServletActionContext.getResponse();
		op=request.getParameter("op");
		if(!"".equals(op)&&op!=null){
			if("findalltable".equals(op)){
				findalltable(request,response);
			}else if("backup".equals(op)){
				backup(request,response);
			}else if("restore".equals(op)){
				restore(request,response);
			}else if("backupall".equals(op)){
				backupall(request,response);
			}else if("showdatabasebackup".equals(op)){
				showdatabasebackup(request,response);
			}else if("restorefromweb".equals(op)){
				restorefromweb(request,response);
			}
		}
		return Action.SUCCESS;
	}

	private void restorefromweb(HttpServletRequest request,
			HttpServletResponse response) {
		String tablename=request.getParameter("tablename");
		//mysqldump -u用户名 -p密码 -h主机 数据库 < 路径
		StringBuffer sb=new StringBuffer();
		GetUrlUtil guu=new GetUrlUtil();
		String realpath=guu.showURl();
		sb.append("cmd /c c:\\mysql");
	    sb.append(" -uroot ");
	    sb.append(" -pa ");
	    sb.append(" haipumi ");
	    sb.append(" <"+realpath+"\\haipumi_database_backup\\"+tablename+".sql");
	    //mysql -u root –password=root密码 数据库名 < 备份文件.sql
	    String javaExecute = sb.toString();// 在CMD中执行的字符串
	    try {
	        Process p = Runtime.getRuntime().exec(javaExecute);
	        p.wait();
	        int ret=p.exitValue();
	        System.out.println("从"+tablename+"恢复了数据库\n信息"+ret);
	    } catch (IOException e) {
	        e.printStackTrace();
	    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    
	}

	private void showdatabasebackup(HttpServletRequest request,
			HttpServletResponse response) {
		String[] filelists=null;;
		try {
			String tablename=request.getParameter("tablename");
//		String path="D:\\tomcat\\apache-tomcat-6.0.33\\webapps\\haipumiBate2.0\\haipumi_database_backup";
			GetUrlUtil guu=new GetUrlUtil();
			String realpath=guu.showURl();
			String path=realpath+"\\haipumi_database_backup\\";
			String filelist=ZipTool.getFileNames(path,tablename+".sql");
			int result=0;
			result=filelist.indexOf(",");
			filelists = null;
			if(result>=0){
				filelists=filelist.split(",");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jm.setCode(0);
			jm.setMsg("由于："+e.getMessage());
		}
		jm.setCode(1);
		jm.setMsg("该表暂时不存在备份信息");
		jm.setObj(filelists);
	}

	private void backupall(HttpServletRequest request,
			HttpServletResponse response) {
		//开始备份
		StringBuffer sb=new StringBuffer();
		
		
		GetUrlUtil guu=new GetUrlUtil();
		String realpath=guu.showURl();
		//TODO   改为中间分隔符可变
//				String[] paths=path.split("\\");
//				String realpath=null;
//				for(int i=0;i<paths.length-5;i++){
//					realpath+=paths[i]+"\\";
//				}
//				System.out.println(realpath);
		//String realpath=(path.substring(0, path.length()-34)).replace("\\", "\\\\");
		String tablename="allData";
		sb.append("cmd /c c:\\mysqldump");
	    sb.append(" -uroot ");
	    sb.append(" -pa ");
	    sb.append(" haipumi ");
	    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
	    String savedate=sdf.format(new Date());
	    sb.append(" >"+realpath+"\\haipumi_database_backup\\"+savedate+"_haipumi_backup_"+tablename+".sql");
	    String javaExecute = sb.toString();// 在CMD中执行的字符串
	    try {
	        Process p = Runtime.getRuntime().exec(javaExecute);
	        LogUtil.log.info(tablename+"数据导出到文件"+realpath+"\\haipumi_database_backup\\haipumi_backup_"+tablename);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    jm.setCode(1);
	    jm.setMsg("haipumi_database_backup/"+savedate+"_haipumi_backup_"+tablename+".sql");
			    
	}

	private void restore(HttpServletRequest request,
			HttpServletResponse response) {
		
	}

	private void backup(HttpServletRequest request, HttpServletResponse response) {
		String tablename=null;
		tablename=request.getParameter("tablename");
		//开始备份
		StringBuffer sb=new StringBuffer();
		GetUrlUtil guu=new GetUrlUtil();
		String realpath=guu.showURl();
		//TODO   改为中间分隔符可变
//		String[] paths=path.split("\\");
//		String realpath=null;
//		for(int i=0;i<paths.length-5;i++){
//			realpath+=paths[i]+"\\";
//		}
//		System.out.println(realpath);
		//String realpath=(path.substring(0, path.length()-34)).replace("\\", "\\\\");
		sb.append("cmd /c c:/mysqldump");
	    sb.append(" -uroot ");
	    sb.append(" -pa ");
	    sb.append(" haipumi ");
	    sb.append(tablename);
	    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
	    String savedate=sdf.format(new Date());
	    sb.append(" >"+realpath+"/haipumi_database_backup/"+savedate+"_haipumi_backup_"+tablename+".sql");
	    String javaExecute = sb.toString();// 在CMD中执行的字符串
	    try {
	        Process p = Runtime.getRuntime().exec(javaExecute);
	        //System.out.println("数据已导出到文件");
	        LogUtil.log.info(tablename+"数据导出到文件"+realpath+"\\haipumi_database_backup\\haipumi_backup_"+tablename);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    jm.setCode(1);
	    jm.setMsg("haipumi_database_backup/"+savedate+"_haipumi_backup_"+tablename+".sql");
	}

	private void findalltable(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session=request.getSession();
		List<haipumi_databasetable>tables=null;
		tables=databaseBiz.findalltables();
		if(tables!=null){
			jm.setCode(1);
			jm.setObj(tables);
			session.setAttribute(CommonData.TABLES, tables);
		}else{
			jm.setCode(0);
		}
	}

}
